<template>
  <div class="add">
    <!-- 添加打印机 -->
    <a-modal v-model:visible="addVisible" okText="确定" cancelText="取消" @cancel="cancel" @ok="submit" :centered="true"
      title="添加打印机">
      <div class="modal_content_add">
        <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 14 }">
          <a-form-item label="选择打印机" name="printerName">
            <a-select v-model:value="formState.printerName" placeholder="请选择打印机" @change="handleChange">
              <a-select-option :value="item.name" v-for="item in pintList" :key="item.name">{{ item.name
}}</a-select-option>
            </a-select>
            <!-- 由于安徽团队打印机获取不到url，暂时改下 -->
            <!-- <a-select v-model:value="formState.printerName" placeholder="请选择打印机" @change="handleChange">
              <a-select-option :value="item.url" v-for="item in pintList" :key="item.url">{{ item.name
}}</a-select-option>
            </a-select> -->
          </a-form-item>
          <a-form-item label="是否启用" name="isInternetPrint">
            <a-radio-group v-model:value="formState.isInternetPrint">
              <a-radio value="1">启用</a-radio>
              <a-radio value="2">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item ref="name" label="位置" name="printerPosition">
            <a-input placeholder="请输入打印机位置,限制两百个字符" v-model:value="formState.printerPosition" />
          </a-form-item>
          <a-form-item label="图标" name="printerIcon">
            <a-input @click="selectIcon" v-model:value="formState.printerIcon" placeholder="请选择打印机图标">
              <template #suffix>
                <DownOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item label="使用范围" name="accessUnitName">
            <a-input-search @search="selectDept" enter-button="添加" v-model:value="formState.accessUnitName"
              placeholder="添加使用范围">
            </a-input-search>
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="formState.remark" placeholder="限制两百个字符" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <!-- 选择打印机图标 -->
    <a-modal v-model:visible="iconVisible" okText="确定" cancelText="取消" :centered="true" title="选择打印机图标" @ok="submitIcon"
      @cancel="cancelIcon">
      <div class="modal_content_icon">
        <p>从以下列表中选择一个打印机图标</p>
        <div class="icon_list">
          <a-radio-group v-model:value="formState.printerIconAudio">
            <div class="icon_item" v-for="(item, index) in pintIconList" :key="index">
              <img :src="item.icon" alt="">
              <a-radio :value="item.value">
              </a-radio>
            </div>
          </a-radio-group>
        </div>
      </div>
    </a-modal>
    <!-- 添加使用范围 -->
    <a-modal width="800px" class="dialog_dept" v-if="deptVisible" v-model:visible="deptVisible" okText="确定"
      cancelText="取消" :centered="true" title="添加使用范围" @ok="submitDept" @cancel="cancelDept">
      <div class="modal_content_dept">
        <div class="dept_left">
          <div class="dept_left_top">
            <a-input placeholder="请输入内容" v-model:value="searchStr">
              <template #suffix>
                <SearchOutlined @search="onSearch" style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input>
            <a-button type="primary" @click="onSearch">查询</a-button>
          </div>
          <div class="dept_left_bottom">
            <a-tree :auto-expand-parent="autoExpandParent" checkable @check="onCheckedKeys" :checkStrictly="true"
              :field-names="fieldNames" v-model:checkedKeys="checkedKeys" v-model:expandedKeys="expandedKeys"
              :load-data="onLoadData" :tree-data="treeData">
            </a-tree>
          </div>
        </div>
        <div class="dept_right">
          <div class="dept_right_top">
            <span>已选择</span>
          </div>
          <div class="dept_right_bottom">
            <li v-for="item in checkedNodes" :key="item">{{ item }}</li>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
const { BrowserWindow, webContents } = require('@electron/remote')
import { rules } from './column'
import api from '@/api/pint'
import { SearchOutlined, DownOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { getPintList } from '@/pint'
export default {
  components: {
    SearchOutlined,
    DownOutlined,
  },
  data() {
    return {
      addVisible: false,
      // 添加打印机
      rules: rules,
      formState: {
        printStationId: "",
        fid: '',
        printerName: undefined,
        isInternetPrint: "1",
        printerPosition: "",
        printerIcon: "",
        printerIconAudio: "",
        accessUnitId: "1,2",
        remark: "",
      },
      state: JSON.parse(localStorage.getItem('state')) || {},
      pintList: [],
      pintIconList: [
        {
          icon: require('../../assets/image/1672026475064.jpg'),
          name: '立式',
          value: '0'
        },
        {
          icon: require('../../assets/image/1672026579766.jpg'),
          name: '台式',
          value: '1'
        },
      ],
      // 选择打印机图标
      iconVisible: false,
      iconValue: "",
      // 添加使用范围
      deptVisible: false,
      fieldNames: {
        children: 'children',
        title: 'name',
        key: 'id'
      },


      backupsExpandedKeys: [],
      autoExpandParent: true,
      defaultExpandAll: true,
      searchStr: '',
      searchValue: '',
      expandedKeys: [],
      checkedKeys: [],
      checkedNodes: [],
      treeData: []

    }
  },
  props: {
    addVisiblePrint: Boolean,
    default: "",
    getPrintList: {
      type: Function,
      default: () => { }
    }
  },
  watch: {
    addVisiblePrint(val) {
      this.addVisible = val;
      if (val) {
        this.pintList = getPintList(BrowserWindow)
        console.log('pintList',this.pintList)
      } 
    },
  },
  methods: {
    getParentKey(key, tree) {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (getParentKey(key, node.children)) {
            parentKey = getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        dataList.push({
          key,
          title: key,
        });
        if (node.children) {
          this.generateList(node.children);
        }
      }
    },
    // 确定
    submit() {
      this.$refs.formRef
        .validate()
        .then(() => {
          let postData = JSON.parse(JSON.stringify(this.formState))
          postData.printerIcon = this.formState.printerIconAudio
          postData.printStationId = this.state.printStationId
          api.addPrinterList(postData).then(res => {
            message.success('打印机添加完成！');
            this.cancel()
            this.getPrintList()
          })
        })
        .catch((error) => {
          console.log('error', error);
        });

    },

    handleChange(value) {
      console.log('change',value)
      this.formState.fid = value;
      // 由于安徽团队打印机获取不到url，暂时改下
      // this.formState.printerName = this.pintList.filter(item => item.url === value)[0].name
      this.formState.printerName = this.pintList.filter(item => item.name === value)[0].name
    },
    // 取消
    cancel() {
      this.$refs.formRef.resetFields();
      this.$emit("setValue", false);
    },
    // 点击搜索进行模糊筛选
    onSearch() {
      const _this = this;
      _this.searchValue = _this.searchStr;

      if (_this.searchValue === '') {
        _this.expandedKeys = [];
      } else {
        _this.expandedKeys = [];
        _this.backupsExpandedKeys = [];
        let candidateKeysList = _this.getkeyList(_this.searchValue, _this.treeData, []);
        candidateKeysList.map(
          item => {
            let key = _this.getParentKey(item, this.treeData);
            if (key && !_this.backupsExpandedKeys.some(item => item === key)) {
              _this.backupsExpandedKeys.push(key);
            }
          }
        )
        let length = this.backupsExpandedKeys.length;

        for (let i = 0; i < length; i++) {
          _this.getAllParentKey(_this.backupsExpandedKeys[i], _this.treeData)
        }
        _this.expandedKeys = _this.backupsExpandedKeys.slice();
        _this.autoExpandParent = true
      }
    },
    // 获取节点中含有value的所有key集合
    getkeyList(value, tree, keyList) {
      for (let i = 0; i < tree.length; i++) {
        let node = tree[i];
        node.scopedSlots = { name: 'name' }
        if (node.name.indexOf(value) > -1) {
          keyList.push(node.id);
        }
        if (node.children) {
          this.getkeyList(value, node.children, keyList);
        }
      }
      return keyList;
    },
    // 该递归主要用于获取key的父亲节点的key值
    getParentKey(key, tree) {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.id === key)) {
            parentKey = node.id;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    // 获取该节点的所有祖先节点
    getAllParentKey(key, tree) {
      let parentKey
      if (key) {
        parentKey = this.getParentKey(key, tree);
        if (parentKey) {
          if (!this.backupsExpandedKeys.some(item => item === parentKey)) {
            this.backupsExpandedKeys.push(parentKey)
          }
          this.getAllParentKey(parentKey, tree)
        }
      }
    },
    onCheckedKeys(checkedKeys, e) {
      console.error('onCheckedKeys',e)
      this.checkedNodes = e.checkedNodes.map(item => item.name)
    },
    // 选择打印机图标
    selectIcon() {
      this.iconVisible = true;
    },
    // 取消选择
    cancelIcon() {
      this.iconValue = false;
      this.iconVisible = false;
    },
    // 确定选择
    submitIcon() {
      if (this.formState.printerIconAudio) {
        this.formState.printerIcon = this.pintIconList.filter(item => item.value === this.formState.printerIconAudio)[0].name
        this.iconVisible = false;
      }
      else {
        this.$message.warning('请选择一个图标');
      }
    },
    //异步加载组织
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode) {
          if (treeNode.dataRef.children) {
            resolve();
            return;
          }
          api.organizationFramework({ orgId: treeNode.dataRef.id }).then(res => {
            treeNode.dataRef.children = res.data
            res.data.forEach(item => {
              item.isLeaf = !!!(item.isLeaf === 'N')
            });
            this.treeData = [...this.treeData];
            resolve();
          })
        } else {
          api.organizationFramework({ orgId: '' }).then(res => {
            res.data.forEach(item => {
              item.isLeaf = !!!(item.isLeaf === 'N')
            });
            this.treeData = res.data
            resolve();
          })
        }
      });
    },
    // 添加使用范围
    selectDept() {
      this.deptVisible = true;
      this.onLoadData()
    },
    // 取消选择
    cancelDept() {
      this.treeData = [];

      this.deptVisible = false;
    },
    // 确定选择
    submitDept() {
      if (this.checkedKeys && this.checkedKeys.checked.length) {
        this.formState.accessUnitId = this.checkedKeys.checked.join()
        this.formState.accessUnitName = this.checkedNodes.join()
        this.deptVisible = false;
      }
      else {
        this.$message.warning('请选择要添加的部门');
      }
    }
  }
}
</script>

<style>

</style>